package com.yzh.wanandroid.component.fragment

import android.view.View
import android.widget.Toast
import androidx.navigation.Navigation
import com.yzh.core.navigation.NavHostFragment
import com.yzh.wanandroid.R
import com.yzh.wanandroid.base.MvvmFragment
import com.yzh.wanandroid.databinding.FragmentLoginBinding
import com.yzh.wanandroid.utils.*
import com.yzh.wanandroid.view.LoadingDialog
import com.yzh.wanandroid.vm.LoginFragmentVm

class LoginFragment : MvvmFragment<FragmentLoginBinding, LoginFragmentVm>() {

    private val TAG = "LoginFragment"

    override fun initViewModel(): LoginFragmentVm = createViewModel()

    override fun getLayoutId() = R.layout.fragment_login

    private val mLoadingStateDialog: LoadingDialog by lazy { LoadingDialog(requireContext()) }

    override fun initView(view: View) {
        initTitle()
    }

    private fun initTitle() {
        mBinding.run {
            loginTitle.titleText.setText(R.string.user_login)
            loginTitle.toolbar.navigationIcon = requireActivity().getDrawable(R.drawable.arrow_back)
            loginTitle.toolbar.setNavigationOnClickListener {
                requireActivity().onBackPressed()
            }
        }
    }

    override fun initData() {
        mBinding.run {
            loginFragment = this@LoginFragment
            mViewModel.mLoginData.observe(this@LoginFragment) {
                when (it?.loadingState) {
                    LOADING -> mLoadingStateDialog.show()
                    SUCCESS -> onLoginSuccess()
                    ERROR -> onLoginFail(it.message)
                }
            }
        }
    }

    fun onLoginClick() {
        mBinding.run {
            mViewModel.login(
                this@LoginFragment,
                etUsername.text.toString(),
                etPassword.text.toString()
            )
        }
    }

    private fun onLoginSuccess() {
        Toast.makeText(activity, R.string.login_success, Toast.LENGTH_SHORT).show()
        mLoadingStateDialog.cancel()
        NavHostFragment.findNavController(this).navigateUp()
    }

    private fun onLoginFail(errorMessage: String) {
        mLoadingStateDialog.cancel()
        Toast.makeText(activity, errorMessage, Toast.LENGTH_SHORT).show()
    }

    fun jumpToRegisterFragment(view: View) {
        Navigation.findNavController(view).navigate(LoginFragmentDirections.toRegister())
    }
}